package com.vstyran.radio.managers
{
	import com.vstyran.radio.events.MusicEvent;
	import com.vstyran.radio.vos.MetaData;
	import com.vstyran.radio.vos.MusicChunk;
	
	import flash.events.Event;
	import flash.events.SampleDataEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	
	public class ClientManager
	{
		public function ClientManager()
		{
			radioManager = new RadioManager();
			radioManager.publisher = false;
			radioManager.initConnection();
			radioManager.addEventListener(MusicEvent.BUFFER_READY, bufferReadyHandler);
			
			sound = new Sound();
			sound.addEventListener(SampleDataEvent.SAMPLE_DATA, sampleDataReceiver);
		}
		
		[Bindable]
		public var radioManager:RadioManager;
		
		private var chanel:SoundChannel;
		
		private var sound:Sound;
		
		private var _volume:Number = 1;

		[Bindable]
		public function get volume():Number
		{
			return _volume;
		}

		public function set volume(value:Number):void
		{
			_volume = value;
			
			if(chanel)
				chanel.soundTransform = new SoundTransform(_volume);
		}

		
		public function listen():void
		{
			radioManager.startBuffering();
		}
		
		public function stop():void
		{
			radioManager.stopBuffering();
		}
		
		protected function bufferReadyHandler(event:MusicEvent):void
		{
			if(!chanel)
			{
				chanel = sound.play();
				chanel.soundTransform = new SoundTransform(_volume);
				chanel.addEventListener(Event.SOUND_COMPLETE, completeHandler);
			}
		}
		
		protected function sampleDataReceiver(event:SampleDataEvent):void
		{
			var chunk:MusicChunk = radioManager.extractBufferChunk();
			if(!chunk)
			{
				chanel.stop();
				chanel = null;
				return;
			}
			else
			{
				event.data.writeBytes(chunk.bytes);
			}
		}
		
		protected function completeHandler(event:Event):void
		{
			chanel = null;
		}
		
		[Bindable]
		public var metaManager:MetaManager = new MetaManager();
		
		public function like():void
		{
			metaManager.send(new MetaData(radioManager.peerId, radioManager.trackName, true));
		}
		
		public function unlike():void
		{
			metaManager.send(new MetaData(radioManager.peerId, radioManager.trackName, false));
		}
	}
}